﻿/////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009 Eric Bowen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
// associated documentation files (the "Software"), to deal in the Software without restriction, including 
// without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
// copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the 
// following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial 
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Author's blog: http://blog.scrappydog.com
// Updated source code available:  http://scrappydb.codeplex.com
/////////////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Reflection;
using Amazon.SimpleDB.Model;
using ScrappyDB.Attributes;
using ScrappyDB.BaseClasses;
using ScrappyDB.Utilities;
using Attribute = Amazon.SimpleDB.Model.Attribute;

namespace ScrappyDB
{
    public partial class Db
    {
        public T DeleteOrphanProperties<T>(Guid id) where T : class, new()
        {
            return DeleteOrphanProperties<T>(id.ToString());
        }

        public T DeleteOrphanProperties<T>(string id) where T : class, new()
        {
            Log.Debug("DB.DeleteOrphanProperties Start: " + DateTime.Now.ToLongTimeString());

            var o = new T();

            string domainName = EntityHelper.GetDomainName(o);
            var domain = new Domains(WebCache);
            domain.EnsureDomain(domainName);

            EntityHelper.LoadItemNameProperty(o, id);

            var request = new GetAttributesRequest { DomainName = domainName, ItemName = id,ConsistentRead = true};
            GetAttributesResponse response = Service.GetAttributes(request);

            Log.Info("ScrappyDB.DeleteOrphanProperties<T>: Domain: {0} - Entity: {1} - Id: {2} ", domainName,
                                   EntityHelper.GetEntityName(o), id);

            if (response.IsSetResponseMetadata())
                Utility.TraceResponse(response.ResponseMetadata, response.ToXML());

            if (response.IsSetGetAttributesResult())
            {
                if (response.GetAttributesResult.Attribute.Count == 0)
                {
                    //no result found
                    return null;
                }

                //we got back data... lets populate the object
                GetAttributesResult getAttributesResult = response.GetAttributesResult;
                List<Attribute> attributeList = getAttributesResult.Attribute;

                DeleteOrphans(o, id, attributeList);

            }

            return o;
        }


        private void DeleteOrphans<T>(T o, string id, IEnumerable<Attribute> attributeList) where T : class, new()
        {
            string entityName = EntityHelper.GetEntityName(o);

            string domainName = EntityHelper.GetDomainName(o);
            var domain = new Domains(WebCache);
            domain.EnsureDomain(domainName);

            var request = new DeleteAttributesRequest { DomainName = domainName, ItemName = id };

            foreach (Attribute attribute in attributeList)
            {
                if (attribute.IsSetName())
                {
                    //we only want to cleanup 'EntityName' fields if the [NoEntityName] attribute is set
                    if (o.GetType().GetCustomAttributes(typeof(NoEntityNameFieldAttribute), true).Length == 0 && attribute.Name == "EntityName")
                        continue;

                    PropertyInfo prop = o.GetType().GetProperty(attribute.Name);

                    if (prop == null)
                    {
                        Log.Warn(
                            "DELETING: SimpleDB data attribute '{0}' with value '{2}' (doesn't exist as a property in entity '{1}')",
                            attribute.Name, entityName, attribute.Value);

                        request.Attribute.Add(attribute);
                    }


                }
            }

            DeleteAttributesResponse response = Service.DeleteAttributes(request);

            Log.Info("ScrappyDB.DeleteOrphans<T>: Domain: {0} - Entity: {1} - Id: {2} ", domainName,
                       EntityHelper.GetEntityName(o), id);

            if (response.IsSetResponseMetadata())
                Utility.TraceResponse(response.ResponseMetadata, response.ToXML());


        }


        //private ArrayList PopulateNewArrayList<T>(Attribute attribute, T o)
        //{
        //    var result = new ArrayList();
        //    PropertyInfo prop = o.GetType().GetProperty(attribute.Name);

        //    var existing = (Array)prop.GetValue(o, null);

        //    //create an arraylist of the existing records (if any)
        //    if (existing != null)
        //    {
        //        foreach (object i in existing)
        //        {
        //            result.Add(i);
        //        }
        //    }

        //    //add the new value
        //    result.Add(int.Parse(attribute.Value));

        //    return result;
        //}

    }
}